<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="领养人名称" prop="nickName" label-width="90" v-hasPermi="['showNickName']" style="width: 300px;">
        <el-select v-model="queryParams.nickName" placeholder="请选择领养人名称" clearable>
          <el-option v-for="item in lyrList" :key="item.nickName" :value="item.nickName"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="记录日期" prop="recordDateRange">
        <el-date-picker clearable
          v-model="queryParams.recordDateRange"
          type="daterange"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          placeholder="请选择记录日期">
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="stats-info mb8">
      <div class="stats-content">
        <span class="stats-item">
          <span class="stats-label">订单总金额：</span>
          <span class="stats-number total">{{ totalAmount }} 元</span>
        </span>
        <span>|</span>
        <span class="stats-item">
          <span class="stats-label">订单总数：</span>
          <span class="stats-number total">{{ orderCount }} 条</span>
        </span>
      </div>
    </div>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button type="info" plain icon="Upload" @click="handleImport">导入</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['project:record:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport+'&userId='+upload.userId" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-table v-loading="loading" :data="recordList" @selection-change="handleSelectionChange">
      <el-table-column label="订单日期" align="center" prop="recordDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.recordDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收入金额" align="center" prop="incomeAmount" />
      <el-table-column label="订单数量" align="center" prop="orderCount" />
      <el-table-column label="车辆数量" align="center" prop="vehicleCount" />
      <el-table-column label="领养人" align="center" prop="nickName" v-hasPermi="['showNickName']"/>

<!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
<!--        <template #default="scope">-->
<!--          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['project:record:edit']">修改</el-button>-->
<!--          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['project:record:remove']">删除</el-button>-->
<!--        </template>-->
<!--      </el-table-column>-->
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="recordRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="收入金额" prop="incomeAmount">
          <el-input v-model="form.incomeAmount" placeholder="请输入收入金额" />
        </el-form-item>
        <el-form-item label="记录日期" prop="recordDate">
          <el-date-picker clearable
            v-model="form.recordDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择记录日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Record">
import {listRecord, getRecord, delRecord, addRecord, updateRecord, getTotal} from "@/api/project/record"
import {getToken} from "@/utils/auth.js";
import {lyrGetlist} from "@/api/system/user.js";

const { proxy } = getCurrentInstance()

const recordList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  userId: null,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/project/record/importData"
})

function handleImport() {
  upload.title = "记录导入"
  upload.open = true
  upload.userId = 1
}
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false
  upload.isUploading = false
  proxy.$refs["uploadRef"].handleRemove(file)
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
  getList()
}

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit()
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 15,
    incomeAmount: null,
    orderCount: null,
    vehicleCount: null,
    recordDate: null,
    userId: null,
    createdAt: null,
    updatedAt: null,
    recordDateRange: []
  },
  rules: {
    incomeAmount: [
      { required: true, message: "收入金额不能为空", trigger: "blur" }
    ],
    orderCount: [
      { required: true, message: "订单数量不能为空", trigger: "blur" }
    ],
    vehicleCount: [
      { required: true, message: "车辆数量不能为空", trigger: "blur" }
    ],
    recordDate: [
      { required: true, message: "记录日期不能为空", trigger: "blur" }
    ],
    userId: [
      { required: true, message: "记录归属人ID不能为空", trigger: "blur" }
    ],
    createdAt: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ],
    updatedAt: [
      { required: true, message: "更新时间不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)
const totalAmount = ref(0)
const orderCount = ref(0)

const lyrList = ref([])

/** 查询订单记录列表 */
function getList() {
  loading.value = true
  listRecord(queryParams.value).then(response => {
    recordList.value = response.rows
    total.value = response.total
    loading.value = false
  })
  getTotalFun()

  lyrGetlist({params:{isPage:false}})
      .then(res => {
        console.log(res)
        lyrList.value = res.rows
      })
}
function getTotalFun(){
  getTotal(queryParams.value).then(res => {
    if(res.data){
      console.log(res.data)
      totalAmount.value = res.data.totalAmount
      orderCount.value = res.data.orderCount
    }else {
      totalAmount.value = 0
      orderCount.value = 0
    }
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    recordId: null,
    incomeAmount: null,
    orderCount: null,
    vehicleCount: null,
    recordDate: null,
    userId: null,
    createdAt: null,
    updatedAt: null
  }
  proxy.resetForm("recordRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.recordId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加订单记录"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _recordId = row.recordId || ids.value
  getRecord(_recordId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改订单记录"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["recordRef"].validate(valid => {
    if (valid) {
      if (form.value.recordId != null) {
        updateRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _recordIds = row.recordId || ids.value
  proxy.$modal.confirm('是否确认删除订单记录编号为"' + _recordIds + '"的数据项？').then(function() {
    return delRecord(_recordIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('project/record/export', {
    ...queryParams.value
  }, `record_${new Date().getTime()}.xlsx`)
}

getList()
</script>

<style scoped lang="scss">
/* 新增：统计信息样式 */
.stats-info {
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 8px;
  padding: 15px 20px;
  margin: 15px 0;
  border-left: 4px solid #409eff;
}

.stats-content {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  flex-wrap: wrap;
  gap: 20px;
}

.stats-item {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.stats-label {
  color: #606266;
  font-weight: 500;
  margin-right: 5px;
}

.stats-number {
  font-weight: bold;
  font-size: 16px;
}

.stats-number.total {
  color: #409eff;
}

.stats-number.pre-admit {
  color: #67c23a;
}

.stats-number.paid {
  color: #e6a23c;
}

.stats-divider {
  color: #dcdfe6;
  font-weight: bold;
  margin: 0 10px;
}

@media (max-width: 768px) {
  .stats-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .stats-divider {
    display: none;
  }
}
</style>
